<script lang="ts" setup>
import { Page, useVbenModal } from '@vben/common-ui';
import { ACTION_ICON, TableAction, useVbenVxeGrid, type VxeTableGridOptions } from '#/adapter/vxe-table';
import { useMagicKeys, whenever } from '@vueuse/core';
import { useCheckoutGridColumns } from '#/views/spa/store/data';
import { getInfoStoreWithGroupPage, type InfoStoreApi } from '#/api/spa/store';
import { loginByHeader } from '#/api/shop/shop-auth';
import { message } from 'ant-design-vue';
import { useTabs } from '@vben/hooks';
import { useStoreSwitchStore } from '#/stores/store-switch';
import { useSiteStore } from '#/stores/site';
import { useGroupSwitchStore } from '#/stores/group-switch';
import ThreeLevelSwitch from './three-level-switch.vue';

const { closeOtherTabs, refreshTab } = useTabs();
const storeSwitchStore = useStoreSwitchStore();
const siteStore = useSiteStore();

defineOptions({
  name: 'SPACheckout',
});

const keys = useMagicKeys();
whenever(keys['Alt+KeyP']!, () => {
  modalApi.open();
});

// 三级切换快捷键
whenever(keys['Alt+KeyG']!, () => {
  // 三级切换组件会自己处理快捷键
});

const [Modal, modalApi] = useVbenModal({
  draggable: true,
  overlayBlur: 5,
  footer: false,
  onOpen() {
    // 弹窗打开时才加载数据
    setTimeout(() => {
      gridApi.query();
    }, 100);
  },
  onCancel() {
    modalApi.close();
  },
});

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: {
    columns: useCheckoutGridColumns(),
    height: 'auto',
    pagerConfig: {
      enabled: true,
    },
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getInfoStoreWithGroupPage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
  } as VxeTableGridOptions<InfoStoreApi.InfoStore>,
});

async function handleSwitchStore(store: InfoStoreApi.InfoStore) {
  try {
    // 设置当前门店
    storeSwitchStore.switchStore(store);

    // 如果门店有绑定的站点信息，更新站点信息
    if (store.siteInfo) {
      try {
        const sites = parseSiteInfo(store.siteInfo);
        if (sites.length > 0) {
          // 默认选择第一个站点
          const firstSite = sites[0];
          siteStore.setCurrentSiteInfo(firstSite);
          console.log('已自动切换到第一个站点:', firstSite.siteName);

          // 调用Shop认证接口
          try {
            const groupSwitchStore = useGroupSwitchStore();
            const currentGroupId = groupSwitchStore.getCurrentGroupId();
            const authResult = await loginByHeader(firstSite.siteId, currentGroupId);
            if (authResult) {
              siteStore.setShopAuthInfo(authResult);
              console.log('Shop认证成功:', authResult);
              console.log('认证Token:', authResult.token);
              console.log('过期时间:', new Date(authResult.expires_time * 1000));
            }
          } catch (authError) {
            console.error('Shop认证失败:', authError);
            message.warn('Shop认证失败，但切换已完成');
          }
        }
      } catch (error) {
        console.error('解析门店站点信息失败:', error);
      }
    } else {
      // 如果门店没有绑定站点，清除当前站点信息
      siteStore.clearCurrentSite();
    }

    await closeOtherTabs();
    await refreshTab();
    modalApi?.close();
    message.success(`已成功切换到门店: ${store.storeName}`);
  } catch (error) {
    console.error('切换门店失败:', error);
    message.error('切换门店失败，请重试');
  }
}

function parseSiteInfo(siteInfo: string) {
  try {
    const sites = JSON.parse(siteInfo);
    return Array.isArray(sites) ? sites : [];
  } catch (error) {
    console.error('解析站点信息失败:', error);
    return [];
  }
}

function handleSiteClick(site: any) {
  siteStore.setCurrentSiteInfo(site);
  siteStore.navigateToSite();
  message.success(`已切换到站点: ${site.siteName}`);
}
</script>

<template>
  <Modal class="w-4/5" :title="`门店切换 (Alt+KeyP) - 当前门店: ${storeSwitchStore.getCurrentStoreName()}`">
    <Page auto-content-height>
      <Grid table-title="选择要切换的门店">
        <template #toolbar-tools>
          <div class="flex items-center gap-4">
            <div class="text-sm text-gray-600">
              当前门店:
              <span class="font-medium text-blue-600">
                {{ storeSwitchStore.getCurrentStoreName() }}
              </span>
            </div>
          </div>
        </template>

        <template #siteInfo="{ row }">
          <div v-if="row.siteInfo" class="site-tags">
            <a-tag
              v-for="(site, index) in parseSiteInfo(row.siteInfo)"
              :key="site.siteId"
              :title="`站点名称: ${site.siteName}\n站点域名: ${site.siteDomain || '无'}\n所属集团: ${site.groupName}\n状态: ${site.statusName}`"
              class="site-tag"
              :class="{ 'site-tag-primary': index === 0 }"
              @click="handleSiteClick(site)"
            >
              {{ site.siteName }}
              <span v-if="index === 0" class="ml-1 text-xs">(默认)</span>
            </a-tag>
          </div>
          <span v-else class="text-gray-400">未绑定站点</span>
        </template>

        <template #actions="{ row }">
          <TableAction
            :actions="[
              {
                label: '切换到此门店',
                type: 'primary',
                icon: ACTION_ICON.EDIT,
                auth: ['spa:info-store:update'],
                popConfirm: {
                  title: '确定要切换到门店 ' + row.storeName + ' 吗？',
                  confirm: handleSwitchStore.bind(null, row),
                },
              },
            ]"
          />
        </template>
      </Grid>
    </Page>
  </Modal>

  <!-- 三级切换组件 -->
  <ThreeLevelSwitch />
</template>

<style scoped>
.site-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  max-width: 300px;
}

.site-tag {
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #d9d9d9;
  background-color: #fafafa;
}

.site-tag:hover {
  background-color: #1890ff;
  color: white;
  border-color: #1890ff;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(24, 144, 255, 0.3);
}

.site-tag-primary {
  background-color: #e6f7ff;
  border-color: #1890ff;
  color: #1890ff;
  font-weight: 500;
}
</style>
